package com.chocho.array;

import java.io.*;
import java.util.Scanner;

/**
 * 将稀疏数组保存到磁盘
 * 恢复原来数据时，读取文件进行恢复
 */
public class SparseArrFile {
    static final String fileDir = "sparse.txt"; //文件地址
    static final String split = " "; //数据分割符
    public static void main(String[] args) {
        //生成稀疏数组
        //原始二维数组
        //0：没有棋子，1：黑子，2：白子
        int chessArr[][] = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][4] = 2;
        //二维数组转为稀疏数组
        int sparseArr[][] = SparseArray.toSparseArr(chessArr);

        //写入文件
        wirte(sparseArr);

        //从文件中恢复二维数组
        int sparseArrFromFile[][] = read();
        int arr[][] = SparseArray.toArr(sparseArrFromFile);
        System.out.println("还原后的二维数组:");
        SparseArray.print(arr);
    }

    public static void wirte(int [][]arr){
        try {
            FileWriter writer = new FileWriter(fileDir);
            BufferedWriter buff = new BufferedWriter(writer);

            //二维数组行数、列数
            int r = arr.length;
            int c = arr[0].length;
            buff.write(r + split + c);
            buff.newLine();

            //二维数组数据
            for(int i = 0; i < r; i++){
                for(int j = 0; j < c; j++){
                    buff.write(arr[i][j] + split);
                }
                buff.newLine();
            }

            buff.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static int[][] read(){
        try {
            File file = new File(fileDir);
            Scanner scanner = new Scanner(file);

            //读取行数、列数
            int row = scanner.nextInt();
            int col = scanner.nextInt();

            //创建二维数组
            int [][]arr = new int[row][col];
            for(int i = 0; i < row; i++){
                for(int j = 0; j < col; j++){
                    arr[i][j] = scanner.nextInt();
                }
            }

            scanner.close();
            return arr;
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
        return new int[0][0];
    }
}
